#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

typedef struct {
    unsigned int ip1:8;
    unsigned int ip2:8;
    unsigned int ip3:8;
    unsigned int ip4:8;
}IP;

unsigned int BytesToLong(unsigned int a ,unsigned int b ,unsigned int c,unsigned int d) {
    return (unsigned int)a << 24 | (unsigned int)b << 16 | (unsigned int)c << 8 | d;
}

int main() {
    FILE *fp,*fw;
    int ch;
    //load
    if((fp = fopen("./17monipdb.dat","rb")) == NULL) {
       printf("the 17monipdb.dat can not be opened.\n");
       return 1;
    }
    if((fw = fopen("./chn.txt","rb+")) == NULL) {
       printf("chn.txt can not be opened.\n");
       return 1;
    }
    long fileLength = 0;
    fseek(fp,0,SEEK_SET);
    fseek(fp,0,SEEK_END);
    fileLength = ftell(fp);
    fseek(fp,0,SEEK_SET);
    printf("Load %ld bytes success\n",fileLength);
    ch = fgetc(fp);
    int index = 0;
    char *dataBuffer = (char *)malloc(sizeof(char)*fileLength);
    while(ch != EOF) {
        dataBuffer[index] = ch;
        index++;
        ch = fgetc(fp);
    }
    fclose(fp);
    unsigned int uiIndexLen= 0;
    memcpy(&uiIndexLen,&dataBuffer[0],4);
    uiIndexLen = ntohl(uiIndexLen);
    char *pIPIndex = &dataBuffer[4];
    char *pIPData = &dataBuffer[uiIndexLen];

    //find
    int iFirst = 0;
    int iStart = 0;
    memcpy(&iStart,pIPIndex + (iFirst * 4),4);
    int iMaxComLen = pIPData - pIPIndex - 1024 - 4;
    unsigned int ucIndexLength = 0;
    int iIndexOffset = -1;
    int total = 0;
    IP ip;
    for(iStart = iStart * 8 + 1024;iStart < iMaxComLen;iStart += 8) {
      unsigned int uiCurrIP = 0;
      iIndexOffset = 0;
      ucIndexLength = 0;
      memcpy(&uiCurrIP,pIPIndex+iStart,4);
      uiCurrIP = ntohl(uiCurrIP);
      memcpy(&iIndexOffset, pIPIndex+iStart+4, 3);
      memcpy(&ucIndexLength, pIPIndex+iStart+7, 1);
      char *area = (char *)malloc(sizeof(char) * ucIndexLength);
      for(int i = 0;i < 6;i++) {
         area[i] = pIPData[iIndexOffset - 1024 + i];
      }
      char *china = "中国";
      char *chinaese = "CHINAM";
      ip.ip1 = (uiCurrIP&0xff000000)>>24;
      ip.ip2 = (uiCurrIP&0x00ff0000)>>16;
      ip.ip3 = (uiCurrIP&0x0000ff00)>>8;
      ip.ip4 = (uiCurrIP&0x000000ff);
      if(strcmp(china,area) == 0 || strcmp(chinaese,area) == 0) {
           total += 1;
           fwrite(&ip,sizeof(ip),1,fw);
      }
      free(area);
    }
    rewind(fw);
    if(fread(&ip,sizeof(ip),10,fw)) {
        printf("read:%u.%u.%u.0/24\n",ip.ip1,ip.ip2,ip.ip3);
    }else {
        printf("read file failed !");
    }
    fclose(fw);
    free(dataBuffer);
    printf("End read file content!\n");
    return 0;
}
